﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class TakeInfo
{
	public EventlineTake take;
	//public float length; 이벤트라인 업데이트로 legnth를 알수없음. endofplay받아서 처리할것
}

public enum ETake
{
	idle01,
	idle02,
	attack01,
	damage01,
	skill01,
	skill01_S,
	support_attack01,
	support_guard01,
	down01,
	downloop01,
	standup01,
	victory01,
	enterstage01,
	die01,
	forward01,
	Max ,
}

public partial class PawnManifest : MonoBehaviour {

	//	이번 시연에서 필살기 미사용
	//static string[] takeNames = { "idle01", "idle02", "attack01", "damage01", "skill01", "support_attack01", "support_guard01", "down01", "downloop01", "ultimate01", "standup01", "victory01" , "enterstage01" , "die01"};
	//static string[] takeNames = { "idle01", "idle02", "attack01", "damage01", "skill01", "support_attack01", "support_guard01", "down01", "downloop01", "standup01", "victory01", "enterstage01", "die01" };
	public Vector3 originalPos;//최초 위치//
	public Quaternion originalRot;//최초 방향//
	Dictionary<ETake ,TakeInfo> takeDic = new Dictionary<ETake, TakeInfo>();
	UnityEngine.Object[] actorMe;
	public PawnManifest targetManifest;//일반적으로 공격 타겟 or 원호방어자일때는 상대방 공격자//
	public PawnManifest supportDefManifest;//원호 방어자//
	public BattlePawn parentPawn;
	public int damageToTarget;
	public int hitCount;
	public float healPercent;
	IEventlinePlayer takePlayer;
	public bool isSupportDefMove;//원호 방어 발생시 방어자//
	public bool isAttackToSupportDef; //원호 방어 발생시 공격자//
	public bool isSupportAtkMove;// 원호 공격자 일때//
	public Vector3 supportDefPos; // 원호 방어위치와 관련있는 변수//
	public Vector3 vReserve1;// 원호 방어위치와 관련있는 변수//
	public string curTakeName;
	public ETake eCurTake;
	public EventlineTake curTake;
	public bool isPlayingIdle2;
	public	BattleCharInfo charInfo;
	public BProjectile projectile;
	public bool isMovedForward;
	public int supportAtkCount;//원호 공격 발생시 몇번째 원호공격인지..//
	public List<BattlePawn> healTargetList = new List<BattlePawn>();
	public Transform damagePointTrans;
	public Transform castPointTrans;
	public Transform hudHeadTrans;
	public static int curSupportAtkHit;
	public bool isSkillActionEnd;
	GameObject [] weaponGo;
	public bool bEnterStageComplete;
	GameObject positionObject;
	public bool bDoneMoveForNextEnemy;


	new public Transform transform;


	void Awake()
	{
		transform = gameObject.transform;
	}
	void Start()
	{
		//this.StartCoroutine( this.ShowShaodw( true ) );
	}

	public static void LoadTakeInAdvance()
	{
		foreach (ECharModel charModel in Enum.GetValues(typeof(ECharModel)))
		{
			if(charModel== ECharModel.none || charModel== ECharModel.Raksha || charModel== ECharModel.Rudra)
				continue;
			foreach (ETake etake in Enum.GetValues(typeof(ETake)))
			{
				if(etake== ETake.Max)
					continue;
				EventlineTake newTake = Eventline.LoadTake( charModel.ToString() + "/" + etake.ToString() );
			}
		}
	}

	//-----------------------------------------------------------------
	//	For LOD
	//-----------------------------------------------------------------
	bool hasLOD;
	RuntimeMeshChanger				runtimeMeshChangerLink = null;
	public RuntimeMeshChanger GetRuntimeMeshChanger()
	{
		return this.runtimeMeshChangerLink;
	}
	
	//-----------------------------------------------------------------
	//	End
	//-----------------------------------------------------------------

	void PrepareLOD()
	{
		//PawnEventHandler peh = null;
		this.runtimeMeshChangerLink = this.gameObject.GetComponent ( typeof ( RuntimeMeshChanger ) ) as RuntimeMeshChanger;
		if ( this.runtimeMeshChangerLink == null ) {
			hasLOD = false;			
			//peh = gameObject.MakeComponent<PawnEventHandler>();
			//peh.manifest = this;			
			return;
		}
		hasLOD=true;		
		this.runtimeMeshChangerLink.ChangeToLow();

		//peh = this.gameObject.MakeComponent<PawnEventHandler> ();
		//peh.manifest = this;
	}	

	public void Init(BattlePawn _parent, int nIndex, bool isPlayer)
	{
		charInfo = GetComponent<BattleCharInfo>();
		charInfo.ShowShadow();
		PrepareLOD();
		parentPawn = _parent;
		originalPos = transform.position;
		originalRot = transform.rotation;

		positionObject = new GameObject();
		positionObject.name = string.Format("positionGo_{0}",gameObject.name);

		if(hudHeadTrans==null)
			hudHeadTrans = transform.FindChild("HUD_Head");
		if(damagePointTrans==null)
			damagePointTrans = BattleUtil.SearchHierarchyForBone(transform, "Damage_point");
		
		if(charInfo.isCaster) {
			if(castPointTrans==null)
				castPointTrans = BattleUtil.SearchHierarchyForBone(transform, "CastPoint");
			BattleResManager.Instance.LoadProjectile(parentPawn.myModel.ToString(), charInfo.projectileInfo);
		}

		bool bForceCreateWeapon = BattleManager.Instance.bTestStartBattle;

		if(!ResourceManager.Inst.IsChoiceMemberGo(gameObject) || bForceCreateWeapon) {
			if(weaponGo==null) {
				weaponGo = new GameObject[2];
				weaponGo = BattleResManager.AttachWeapon( this.gameObject, charInfo, parentPawn.itemModelID, false);			
			}
		}

		if(actorMe==null) {
			actorMe = new UnityEngine.Object[1];
			actorMe[0] = this.gameObject;
		}

		string takePath="";

		string myModelStrTmp = _parent.myModelStr;
		if(_parent.myModel== ECharModel.Chanter)
			myModelStrTmp += "_M";
		else if(_parent.myModel== ECharModel.Cleric)
			myModelStrTmp += "_W";
		else if(_parent.myModel== ECharModel.Gladiator)
			myModelStrTmp += "_M";
		else if(_parent.myModel== ECharModel.LycanRanger)
			myModelStrTmp += "_M";
		else if(_parent.myModel== ECharModel.Ranger)
			myModelStrTmp += "_W";

		if(BattleManager.Instance.Is5vs5New) {
			takePath = "MassBattle/";
			if(_parent.myModel== ECharModel.Templar)
				myModelStrTmp += "_M";
			if(_parent.myModel== ECharModel.Assassin)
				myModelStrTmp += "_M";
			else if(_parent.myModel== ECharModel.Sorcerer)
				myModelStrTmp += "_W";
			else if(_parent.myModel== ECharModel.Spiritmaster)
				myModelStrTmp += "_W";
		}

		takePath += myModelStrTmp+"/";
//		Debug.Log("takepath  ="+takePath);


		//for(int i=0; i< takeNames.Length; i++)
		foreach (ETake etake in Enum.GetValues(typeof(ETake)))
		{
			if(etake== ETake.Max)
				continue;
			if( takeDic.ContainsKey( etake ) )
				continue;

			string _takeName = etake.ToString();

			EventlineTake newTake = Eventline.LoadTake(takePath+_takeName);
			if( newTake == null )
				continue;
			//Debug.LogError("load take   "+takePath+etake.ToString());
			TakeInfo tinfo = new TakeInfo();
			tinfo.take = newTake;
			//tinfo.length = tinfo.take.NumFrames/(float)tinfo.take.FrameRate;
			//Debug.Log("Take  "+takeName + "   "+ tinfo.length);
			takeDic.Add(etake, tinfo);

			//일단 임시로 entity셋팅해줘야한다//
//			foreach (EventlineTrack track in tinfo.take.TrackValues)
//			{
//				if (track is EventlineTranslationTrack)
//					track.UpdateCache();
//
//				foreach (EventlineAction action in track.Cache)
//				{
//					if (action is EventlineAnimationAction)
//					{
//						(action as EventlineAnimationAction).Entity = GetGameObject();
//					}
//				}
//			}
		}

	}

//	IEnumerator ShowShaodw( bool bOK )
//	{
//		if( bOK == true )
//		{		//	로딩 문제 때문에 특정 시간 이후에 그림자를 활성화 한다.
//			yield return new WaitForSeconds( 2.0f );
//			if( this.charInfo.CircleShadowLink != null )
//				this.charInfo.CircleShadowLink.enabled = true;
//		}
//		else
//		{
//			if( this.charInfo.CircleShadowLink != null )
//				this.charInfo.CircleShadowLink.enabled = false;
//		}
//	}
	

	public void PlayIdleDontStopCurTake()
	{
		PlayEventlineTake(ETake.idle01, true, actorMe, false);
	}

	public void PlayIdle()
	{
		PlayEventlineTake(ETake.idle01,true);
	}

	public bool IsIdleOrDamagePlaying()
	{
		//if(curTakeName=="idle01" || curTakeName=="idle02" || curTakeName=="damage01")
		if(eCurTake== ETake.idle01 || eCurTake== ETake.idle02 || eCurTake== ETake.damage01)
			return true;
		return false;
	}

	public bool IsIdlePlaying()
	{
		//if(curTakeName=="idle01" || curTakeName=="idle02")
		if(eCurTake== ETake.idle01 || eCurTake== ETake.idle02)
			return true;
		return false;
	}

	public bool IsIdle01Playing()
	{
		//if(curTakeName=="idle01")
		if(eCurTake== ETake.idle01)
			return true;
		return false;
	}

	public bool IsSupportDefPlaying()
	{
		//return (curTakeName == "support_guard01");
		return (eCurTake== ETake.support_guard01);
	}

	public bool HasIdle2()
	{
		return takeDic.ContainsKey(ETake.idle02);
	}

	public void PlayIdle2()
	{
		if(takeDic.ContainsKey(ETake.idle02) ) {
			PlayEventlineTake(ETake.idle02,false);
			isPlayingIdle2 = true;
		}
	}

	public void DonePlayIdle2()
	{
		isPlayingIdle2 = false;
		PlayIdle();
	}

	public void PlayStandUp()
	{
		if(takeDic.ContainsKey(ETake.standup01) ) {
			PlayEventlineTake(ETake.standup01,false);
			isPlayingIdle2 = true;
			StopCoroutine("CoPlayIdle2");
			StartCoroutine("CoPlayIdle2",ETake.standup01);
		}
	}

	public void StopCurTake()
	{
		curTakeName = "";
		eCurTake = ETake.Max;
		if(takePlayer!=null)
		{
			takePlayer.Stop();
			takePlayer = null;
		}
		curTake = null;
	}

	public void StopEventLineTween()
	{
		/*
		EventlineTween.Stop(highPolyGo);
		if(highPolyGo!=lowPolyGo)
			EventlineTween.Stop(lowPolyGo);
		 */
		EventlineTween.Stop ( this.gameObject );
	}

	float PlayEventlineTake(ETake _takeEnum, bool isLoop, UnityEngine.Object [] actors, bool bStopCurTake)
	{
		if(isPlayingIdle2) {
			StopCoroutine("CoPlayIdle2");
		}
		if(bStopCurTake)
			StopCurTake();
		curTakeName = _takeEnum.ToString();
		eCurTake = _takeEnum;
		if(!takeDic.ContainsKey(_takeEnum)) {
			Debug.LogError("take dic not contain key "+_takeEnum);
			return 0;
		}
		curTake = takeDic[_takeEnum].take;
//		Debug.Log(gameObject.name +"  PlayEventlineTake  "+curTakeName);
		takePlayer = Eventline.Play ( takeDic[_takeEnum].take, actors, this.gameObject, isLoop);
		
		return 0;//takeDic[_takeEnum].length;
	}

	float PlayEventlineTake(ETake _takeEnum, bool isLoop, UnityEngine.Object [] actors)
	{
		return PlayEventlineTake(_takeEnum, isLoop, actors, true);
	}

	public float PlayEventlineTake(ETake _takeEnum, bool isLoop)
	{
		return PlayEventlineTake(_takeEnum, isLoop, actorMe);
	}

	//////////// Action ///////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////
	//일반 공격//
	public float ActionAttack(BattlePawn targetPawn, int _damage, bool bLookAt)
	{
		Debug.Log("ActionAttack  "+gameObject.name);
		//if(charInfo.isCaster)
		//	parentPawn.isProjectileCasting=true;
		hitCount = 0;
		damageToTarget = _damage;
		targetManifest = targetPawn.pawnManifest;
		if(bLookAt) {
			//BattleUtil.LookAt(transform, targetManifest.transform);
			StopCoroutine("CoOriginalRot");
			StartCoroutine("CoLookatEnemy");
		}

		//	temp code
		//	by jin-hyun
		UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )targetPawn.pawnManifest.gameObject };		
		PlayEventlineTake(ETake.attack01,false, actors);
		//this.StartCoroutine( BattleManager.Instance.ShakeCamera ( this.charInfo, false ) );
		return 0;//takeDic[ETake.attack01].length;
	}

	public void ActionAttack5vs5(BattlePawn targetPawn, int _damage, bool bLookAt)
	{
		hitCount = 0;
		damageToTarget = _damage;
		targetManifest = targetPawn.pawnManifest;

		UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )targetPawn.pawnManifest.gameObject };		
		PlayEventlineTake(ETake.attack01,false, actors);
	}

	//원호 방어자에게 공격//
	public float ActionAttackToSupportDefPawn(BattlePawn targetPawn, BattlePawn supportDefPawn, int _damage)
	{
		Debug.Log("ActionAttackToSupportDefPawn  "+gameObject.name);
		//if(charInfo.isCaster)
		//	parentPawn.isProjectileCasting=true;
		hitCount=0;
		damageToTarget = _damage;
		isAttackToSupportDef=true;
		supportDefManifest = supportDefPawn.pawnManifest;
		targetManifest = targetPawn.pawnManifest;
		StopCoroutine("CoOriginalRot");
		BattleUtil.LookAt(transform, targetPawn.pawnManifest.transform);
		//Object [] actors = {actorMe[0], (Object)supportDefPawn.pawnManifest.GetGameObject()};
		UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )supportDefPawn.pawnManifest.gameObject };
		PlayEventlineTake(ETake.attack01,false,actors);
		//vReserve1 = BattleUtil.GetTargetAttackPos(transform.position, targetPawn.pawnManifest.transform.position, charInfo.targetPosOffset);//상대편 원호 방어 지점//
		supportDefPos = BattleUtil.GetTargetAttackPos(transform.position, targetPawn.pawnManifest.transform.position, charInfo.myRadius + targetPawn.pawnManifest.charInfo.myRadius);//, 2.0f);//나의 공격 이동 지점//
		vReserve1 = (supportDefPos + targetPawn.pawnManifest.transform.position)/2;//적과 아군의 중간 지점으로 들어가자//
		return 0;//takeDic[ETake.attack01].length;
	}

	//원호 공격//
	public float ActionSupportAttack(BattlePawn targetPawn, int _damage, int _supportAtkCount)
	{
		Debug.Log("ActionSupportAttack  "+gameObject.name);
		//if(charInfo.isCaster)
		//	parentPawn.isProjectileCasting=true;
		hitCount = 0;
		supportAtkCount = _supportAtkCount;
		isSupportAtkMove = true;
		damageToTarget = _damage;
		targetManifest = targetPawn.pawnManifest;
		StopCoroutine("CoOriginalRot");
		BattleUtil.LookAt(transform, targetManifest.transform);
		//Object [] actors = {actorMe[0], (Object)targetPawn.pawnManifest.GetGameObject(), (Object)Camera.main.gameObject};
		UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )targetPawn.pawnManifest.gameObject, ( UnityEngine.Object )Camera.main.gameObject };
		PlayEventlineTake(ETake.support_attack01,false, actors);
		BattleManager.Instance.cam.SupportCamFocus(charInfo.isCaster, targetManifest, this);
		return 0;//takeDic[ETake.support_attack01].length;
	}

	//스킬 공격//
	public float ActionSkillAttack(BattlePawn targetPawn, int _damage, bool bLookAt)
	{
		Debug.Log("ActionSkillAttack  "+gameObject.name);
		isSkillActionEnd=false;
		hitCount = 0;
		damageToTarget = _damage;
		targetManifest = targetPawn.pawnManifest;
		//Object [] actors = {actorMe[0], (Object)targetPawn.pawnManifest.GetGameObject()};
		if(parentPawn.isBoss) {//보스는 전체 공격. 카메라가 들어간다.//
			UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )BattleManager.Instance.cameraRoot,( UnityEngine.Object )Camera.main.gameObject };
			PlayEventlineTake(ETake.skill01,false,actors);
		}
		else {
			UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )targetPawn.pawnManifest.gameObject , ( UnityEngine.Object )BattleManager.Instance.cameraRoot};
			PlayEventlineTake(ETake.skill01,false,actors);
		}

		if(bLookAt) {
			StopCoroutine("CoOriginalRot");
			BattleUtil.LookAt(transform, targetManifest.transform);
		}

		CamAtkFocus(false);
		//this.StartCoroutine( BattleManager.Instance.ShakeCamera ( this.charInfo, true ) );
		//Invoke ("EndActionSkill", takeDic[ETake.skill01].length);
		return 0;//takeDic[ETake.skill01].length;
	}

	// 힐 스킬//
	public float ActionSkillHeal(BattlePawn [] targetList, float _healPercent)
	{
		Debug.Log("ActionSkillHeal  "+gameObject.name);
		isSkillActionEnd=false;
		hitCount = 0;
		healPercent = _healPercent;
		healTargetList.Clear();
		List<UnityEngine.Object> actorList = new List<UnityEngine.Object>();
		if(targetList.Length==0) {//이런 상황은 없어야하지만 일단..//
			//healTargetList.Add ( parentPawn);
			//PlayEventlineTake("skill01",false, actorMe);
			healTargetList.Add ( parentPawn);
			for(int i=0; i<4; i++) {
				actorList.Add ( actorMe[0] );
			}
		}
		else {

			healTargetList.Add ( parentPawn);
			actorList.Add( actorMe[0]);
			int nCount=0;
			for(int i=0; i<targetList.Length; i++) {
				if(nCount==4) {
					Debug.LogError("Target Length over 4");
					break;
				}
				if( targetList[ i ].pawnManifest != this) {
					actorList.Add ( ( UnityEngine.Object )targetList[ i ].pawnManifest.gameObject );
					healTargetList.Add ( targetList[ i ] );
					nCount++;
				}
			}
			if(nCount<3)
			{
				for(int i=0; i<3-nCount; i++)
					actorList.Add( actorMe[0]);//인원수를 맞춰주지않으면 이펙트가 엉뚱한데서 뜨므로..일단 나에게 다 넣자//
			}

		}
		actorList.Add ( ( UnityEngine.Object )BattleManager.Instance.cameraRoot );
		PlayEventlineTake(ETake.skill01,false,actorList.ToArray());
		//Invoke ("EndActionSkill", takeDic[ETake.skill01].length);
		return 0;
	}

	void EndActionSkill()
	{
		isSkillActionEnd=true;
	}

	//필살기 공격//
	public float ActionRageSkill(BattlePawn [] targetList)
	{		
		Debug.Log("ActionRageSkill  "+gameObject.name+"  targetListLength="+targetList.Length);
		UnityEngine.Object [] actors = new UnityEngine.Object[7];
		//actors[0] = (Object)GetGameObject();
		actors[ 0 ] = ( UnityEngine.Object )this.gameObject;
		actors[1] = (UnityEngine.Object)BattleManager.Instance.cameraRoot;
		for(int i=0; i<targetList.Length; i++)
			actors[ i + 2 ] = ( UnityEngine.Object )targetList[ i ].pawnManifest.gameObject;
		//actors[i+2] = (UnityEngine.Object)targetList[i].pawnManifest.GetGameObject();
		actors[6] = ( UnityEngine.Object )Camera.main.gameObject;
		BattleManager.Instance.cam.StopCamAtkFocus();
		//PlayEventlineTake("ultimate01",false,actors);
		//return takeDic["ultimate01"].length;	
		return 3.0f;//temp
	}

	//원호 방어//
	void ActionSupportDef(PawnManifest enemy, PawnManifest ally, Vector3 pos)
	{
		Debug.Log("ActionSupportDef  "+gameObject.name);
		isSupportDefMove = true;
		targetManifest = enemy;
		//BattleUtil.LookAt(transform, ally.transform);
		if(enemy.isMovedForward)
			supportDefPos = pos;//적과 아군의 중간 지점//
		else
			supportDefPos = enemy.supportDefPos;//적이 앞으로 이동하지 않았을경우는 원래 적이 공격하는 위치로//
		PlayEventlineTake(ETake.support_guard01,false);
		//StartCoroutine("CoAfterActionSupportDef", takeDic["support_guard01"].length);
	}

	//원호 방어 끝난후 죽는 경우 처리..//
//	IEnumerator CoAfterActionSupportDef(float duration)
//	{
//		yield return new WaitForSeconds(duration);
//		if(parentPawn.isDead)
//			ActionDamaged(0,0);
//		else
//			PlayIdle();
//	}

	//원호 방어 끝난후 죽는 경우 처리..//
	public void EventEndSupportGuard()
	{
		if(parentPawn.isDead)
			ActionDamaged(0,0);
		else
			PlayIdle();
	}

	//데미지 입을때//
	public void ActionDamaged(int damage, int hp)
	{
		//Debug.Log("ActionDamaged  "+gameObject.name+"  hp="+hp);
		if(hp==0) {
			PlayEventlineTake(ETake.die01,false);
		}
		else {
			if(BattleManager.Instance.Is5vs5New) {
			}
			else {
				GameObject middleCam = null;
				if(!BattleSetting.Instance.noCameraShakeInTake)
					middleCam = BattleManager.Instance.cam.middleCam;
				UnityEngine.Object[] actors = { actorMe[ 0 ], (UnityEngine.Object)middleCam };
				PlayEventlineTake(ETake.damage01,false,actors);
			}
		}
	}

	public void ActionDie()
	{
		StartCoroutine("CoActionDie");
	}

	IEnumerator CoActionDie()
	{
		while(!IsIdlePlaying())
			yield return null;
		Debug.Log(name+"    action die ");
		parentPawn.hpBar.gameObject.SetActive(false);
		PlayEventlineTake(ETake.die01,false);
	}

	public void DoneDieTake()
	{
		if(BattleManager.Instance.Is5vs5New) {

		}
		positionObject.SetActive(false);
		StopCurTake();
		parentPawn.hpBar.gameObject.SetActive(false);
		gameObject.SetActive(false);
	}
	///////// Action End ///////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////


	public float GetTakeLength_Damage01()
	{
		return 1.0f;//takeDic[ETake.damage01].length;
	}
	public float GetTakeLength_Ultimate01()
	{
		//return takeDic[ "ultimate01" ].length;
		return 3.0f;//temp
	}
	public float GetTakeLength_EnterStage01()
	{
		return 1.0f;//takeDic[ ETake.enterstage01 ].length;
	}

	public void OnDamage(int _damage, int _hitCount, int _totalDamage)
	{
		bool bSkipDamageAnim = isSupportDefMove;
		parentPawn.OnDamage(_damage, _hitCount, _totalDamage, bSkipDamageAnim);
	}

	public void OnDamageByProjectile(int _damage, float delayDisableCamFocus)
	{
		parentPawn.OnDamage(_damage, 1, _damage, isSupportDefMove);
		//Invoke ("StopCamAtkFocus", 1.0f);
		StartCoroutine("CoDisableCamAtkFocus", delayDisableCamFocus);
	}

	IEnumerator CoDisableCamAtkFocus(float delayDisableCamFocus)
	{
		yield return new WaitForSeconds(delayDisableCamFocus);
		CamAtkFocus(false);
	}


	public void EnterStage(bool bSkipEnterStageTake)
	{
		bEnterStageComplete=false;
		gameObject.SetActive(true);
		if(BattleManager.Instance.Is5vs5New) {
			LeanTween.move(gameObject, Battle5vs5Center.Instance.positionVec[parentPawn.myCurLine, parentPawn.myRow], 1.0f);
			Invoke ( "DoneEnterStage", 1.0f);
			//UnityEngine.Object[] actors = { actorMe[ 0 ], Battle5vs5Center.Instance.positionGo[parentPawn.myCurLine, parentPawn.myRow] };		
			//PlayEventlineTake(ETake.forward01,false, actors);
		}
		else {
			if(!bSkipEnterStageTake && takeDic.ContainsKey(ETake.enterstage01) ) {
				EnterStageMove();
				PlayEventlineTake(ETake.enterstage01, false);
			}
			else
				PlayIdle();
		}
	}

	void DoneEnterStage()
	{
		bEnterStageComplete=true;
		PlayIdleDontStopCurTake();
	}

	public void EnterStageMove()
	{
		if(charInfo.isEnterStageMove)
		{
			transform.position = transform.position - transform.forward * 2.0f;
			LeanTween.move(gameObject, transform.position + transform.forward * 2.0f, 2.0f);
		}
	}

	//공격의 첫 hit시 호출:  melee계열은 이벤트 받을때, caster계열은 발사체 터질때//
	public void FirstHit()
	{
		if(isSupportAtkMove) {
			isSupportAtkMove=false;
			if(parentPawn.myAction== EBattleAction.OverdriveAttack)
			{
				if(BattleManager.Instance.isOverdriveReady)
					BattleUIManager.Instance.SetComboCount();
				return;
			}
			if(supportAtkCount==0)//오버드라이브모드로 들어온 경우 다시 체크. 위 코드에서 걸러지지못하는 상황이 발생시..//
				return;
			curSupportAtkHit++;
			Debug.Log(gameObject.name + "  First Hit    supportAtkCount="+supportAtkCount+"  totalSupportAtkCount="+BattlePawn.totalSupportAtkCount+"  curSupportAtkHit="+curSupportAtkHit);
			if(curSupportAtkHit==1)
				BattleUIManager.Instance.ShowCoAttackText();
			if(curSupportAtkHit>=1 && curSupportAtkHit<=3) {
				BattleUIManager.Instance.ShowSupportAttackTextEffect(curSupportAtkHit);
				if(curSupportAtkHit>=2)
					BattleManager.Instance.cam.SupportAtkCamForward(curSupportAtkHit);
			}
			//if(curSupportAtkHit == BattlePawn.totalSupportAtkCount)
			//	Invoke ("StopSupportCamFocusRotate", 0.5f);
		}
	}

	public void GotoOriginalRot(float fDuration)
	{
		//if(isSupportDefMove)
			StartCoroutine("CoOriginalRot", fDuration);
	}

	IEnumerator CoOriginalRot(float duration)
	{
		yield return new WaitForSeconds(duration+0.02f);
		float sumTime=0;
		while(true)
		{
			sumTime+= Time.deltaTime;

			transform.rotation = Quaternion.Slerp(transform.rotation, originalRot, 3 * Time.deltaTime);
			if(sumTime>1.0f) {
				break;
			}
			yield return null;
		}
		transform.rotation = originalRot;
	} 
	 



	public void CheckSupportAttack()
	{
		if(parentPawn.IsCurActionPawn() && parentPawn.isSupportAtkHappen)
		{
			parentPawn.CheckSupportAttack(targetManifest.parentPawn);
		}
	}

	public void CheckSupportDef()
	{
		if(supportDefManifest!=null) {
			supportDefManifest.ActionSupportDef(this, targetManifest, vReserve1);
		}
	}


	IEnumerator CoLookatEnemy()
	{
		float sumTime=0;
		while(true) {
			sumTime += Time.deltaTime;
			Quaternion quat = Quaternion.LookRotation( targetManifest.originalPos - transform.position);
			if(quat.IsValid())
				transform.rotation = quat;
			if(sumTime > 1.0f)
				break;
			yield return null;
		}
	} 

	public void CamAtkFocus(bool bActivate)
	{
		if(bActivate && eCurTake != ETake.attack01)
			return;
		if(BattleManager.Instance.isBossBattle)
			return;
		//if(parentPawn.isSupportAtkHappen)
		//	return;
		BattleManager.Instance.cam.CamAtkFocus(bActivate, targetManifest);
		
	} 	

	public void SetToOriginalTransform()
	{
		StopCoroutine("CoLookatEnemy");
		transform.position = originalPos;
		transform.rotation = originalRot;
	}

	public void ActionMoveFoward(int nRow, int nStepSize)
	{
		Vector3 newPos = transform.position;
		if(parentPawn.isPlayer)
			newPos.x -= Battle5vs5Center.Instance.gapBetweenLine * nStepSize;
		else
			newPos.x += Battle5vs5Center.Instance.gapBetweenLine * nStepSize;
		positionObject.transform.position = newPos;
		originalPos = positionObject.transform.position;
		transform.rotation = originalRot;
		LeanTween.move(gameObject, positionObject.transform.position, 0.5f);
		Invoke ( "DoneActionMoveFoward", 0.5f);
		//UnityEngine.Object[] actors = { actorMe[ 0 ], Battle5vs5Center.Instance.positionGo[nFrontLine,nRow] };		
		//PlayEventlineTake(ETake.forward01,false, actors);
	}

	void DoneActionMoveFoward()
	{
		parentPawn.myAction= EBattleAction.Nothing;
	}

	public void MoveForNextEnemy()
	{
		bDoneMoveForNextEnemy=false;
		Vector3 newPos = transform.position;
		if(parentPawn.isPlayer)
			newPos.x -= Battle5vs5Center.Instance.gapBetweenLine * 5;
		else
			newPos.x += Battle5vs5Center.Instance.gapBetweenLine * 5;
		positionObject.transform.position = newPos;
		originalPos = positionObject.transform.position;
		transform.rotation = originalRot;
		LeanTween.move(gameObject, positionObject.transform.position, 1.0f);
		Invoke ( "DoneMoveForNextEnemy", 1.0f);
	}

	void DoneMoveForNextEnemy()
	{
		bDoneMoveForNextEnemy=true;
	}

}
